#include "SeqList.h"

// 顺序表初始化
void SLInit(SL *ps)
{
    ps->arr = NULL;
    ps->size = ps->capacity = 0;
}

// 扩容
void SLCheckCapacity(SL *ps)
{
    if (ps->size == ps->capacity)
    {
        SLDataType NewCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
        SLDataType *temp = (SLDataType *)realloc(ps->arr, NewCapacity * sizeof(SLDataType));
        if (temp == NULL)
        {
            perror("realloc");
            exit(1);
        }
        else
        {
            ps->arr = temp;
            ps->capacity = NewCapacity;
        }
    }
}

// 顺序表的打印
void SLPrint(SL s)
{
    for (int i = 0; i < s.size; i++)
    {
        printf("%d ", s.arr[i]);
    }
    printf("\n");
}

// 头插
void SLPushFront(SL *ps, SLDataType x)
{
    assert(ps);
    SLCheckCapacity(ps);
    for (int i = ps->size; i > 0; i--)
    {
        ps->arr[i] = ps->arr[i - 1];
    }
    ps->arr[0] = x;
    ps->size++;
}

// 尾插
void SLPushBack(SL *ps, SLDataType x)
{
    assert(ps);
    SLCheckCapacity(ps);
    ps->arr[ps->size++] = x;
}

// 指定位置插入
void SLInsert(SL *ps, int pos, SLDataType x)
{
    assert(ps);
    assert(pos >= 0 && pos <= ps->size);
    for (int i = ps->size; i > pos; i--)
    {
        ps->arr[i] = ps->arr[i - 1];
    }
    ps->arr[pos] = x;
    ps->size++;
}

// 头删
void SLPopFront(SL *ps)
{
    assert(ps);
    assert(ps->size);
    for (int i = 0; i < ps->size; i++)
    {
        ps->arr[i] = ps->arr[i + 1];
    }
    ps->size--;
}

// 尾删
void SLPopBack(SL *ps)
{
    assert(ps);
    assert(ps->size);
    ps->size--;
}

// 指定位置删除
void SLErase(SL *ps, int pos)
{
    assert(ps);
    assert(pos >= 0 && pos < ps->size);
    for (int i = pos; i < ps->size; i++)
    {
        ps->arr[i] = ps->arr[i + 1];
    }
    ps->size--;
}

// 顺序表的查找
int SLFind(SL *ps, SLDataType x)
{
    assert(ps);
    for (int i = 0; i < ps->size; i++)
    {
        if (ps->arr[i] == x)
            return i;
    }
    return -1;
}

// 顺序表的销毁
void SLDestroy(SL *ps)
{
    if (ps->arr)
    {
        free(ps->arr);
    }
    ps->arr = NULL;
    ps->size = ps->capacity = 0;
}